package com.itheima.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Mapper.ShoppingCartMapper;
import com.itheima.Service.ShoppingCartService;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.ShoppingCart;
import com.itheima.pojo.ShoppingCartQueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    @Transactional
    public void add(ShoppingCart cartItem) {
        // 检查商品是否已在购物车中
        ShoppingCart existingItem = shoppingCartMapper.getByUserAndProduct(
                cartItem.getUserId(), cartItem.getProductId());
        
        if (existingItem != null) {
            // 已存在则更新数量
            existingItem.setQuantity(existingItem.getQuantity() + cartItem.getQuantity());
            existingItem.setUpdateTime(LocalDateTime.now());
            shoppingCartMapper.update(existingItem);
        } else {
            // 不存在则新增
            cartItem.setCreateTime(LocalDateTime.now());
            cartItem.setUpdateTime(LocalDateTime.now());
            shoppingCartMapper.insert(cartItem);
        }
    }

    @Override
    public void update(ShoppingCart cartItem) {
        cartItem.setUpdateTime(LocalDateTime.now());
        shoppingCartMapper.update(cartItem);
    }

    @Override
    public void delete(Integer userId, Integer productId) {
        shoppingCartMapper.delete(userId, productId);
    }

    @Override
    public void batchDelete(Integer userId, List<Integer> productIds) {
        shoppingCartMapper.batchDelete(userId, productIds);
    }

    @Override
    public void clear(Integer userId) {
        shoppingCartMapper.clear(userId);
    }

    @Override
    public PageResult<ShoppingCart> list(ShoppingCartQueryParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<ShoppingCart> cartItems = shoppingCartMapper.list(param.getUserId());
        Page<ShoppingCart> page = (Page<ShoppingCart>) cartItems;
        return new PageResult<>((int) page.getTotal(), cartItems);
    }
}